package com.x.error;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * ClassName: GlobalExceptionHandler
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.09.14 0:47
 */
//发生异常就会走该类下的handler方法

@ControllerAdvice //可以返回视图资源，用来转发重定向
@RestControllerAdvice //@ControllerAdvice + @ResponseBody == 返回JSON字符串
public class GlobalExceptionHandler {

    @ExceptionHandler(ArithmeticException.class)
    public Object ArithmeticExceptionHandler(ArithmeticException e){
        String message = e.getMessage();
        System.out.println(message);
        return message;
        // by zero
    }

    @ExceptionHandler(NullPointerException.class)
    public Object NullPointerExceptionHandler(NullPointerException e){
        String message = e.getMessage();
        System.out.println(message);
        return message;
        // Cannot invoke "String.toString()" because "name" is null
    }
}
